package com.blue.utils;


import com.blue.pojo.SendPackageVo;
import javafx.concurrent.Task;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;

import java.applet.Applet;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SendPackageToPath extends Applet {

    byte buffer[] = new byte[5200];
    private String fileName = "", destPath = "", settPort = "";
    private ProgressBar pb;
    private Label barLabel;
    public Button installBtn;

    public SendPackageToPath(SendPackageVo testSendInfoVo, ProgressBar pb, Label barLab) {

        this.fileName = testSendInfoVo.getFileName();
        this.destPath = testSendInfoVo.getFilePath();
        this.pb = pb;
        this.barLabel = barLab;
        this.settPort = testSendInfoVo.getPort();

    }

    /*public Task sendPackageInfoByTask(final String projectName) throws IOException {
        // Label barLabel;
        String zipName = GlobalConfInfo.getProjectMap().get( projectName ).split( "," )[1];

        //String sourceFilePath = System.getProperty( "user.dir" ) + "/package/" + zipName;

        BufferedReader reader = new BufferedReader( new InputStreamReader( this.getClass().getResourceAsStream( "/package/" + zipName ) ) );

        StringBuilder sb = new StringBuilder("");
        sb = new StringBuilder();


        String destFilePath = destPath + "/" + fileName;

        //File sourceFile = new File( sourceFilePath );
        File destFile = new File( destFilePath );


        //FileInputStream fin = new FileInputStream( sourceFile );
        FileOutputStream fout = new FileOutputStream( destFile );
        BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( fout, "utf-8" ) );

        return new Task<Void>() {

            @Override
            protected Void call() throws Exception {

                byte[] bytes = new byte[1024];
                double fileLen = 0, allFileLen = 0;
                double sendRate = 0.0;
                String b = null;
                try {

                    //allFileLen = sourceFile.length();
                    System.out.println( " Source File Size ::" + allFileLen );
                    System.out.println( " 测试路径 ::" + destFilePath );
                    if (!destFile.exists()) {
                        destFile.createNewFile();
                    }

                    // bytes = new byte[1024];
                    while((b = reader.readLine()) != null){
                        //System.out.println(b);
                        sb.append(b);

                        if (isCancelled())
                            break;
                        fileLen = fileLen + bytes.length;
                        sendRate = (fileLen / allFileLen);
//						System.out.println("------- write File Len ::" + fileLen + " all FileLen::" + allFileLen
//								+ " rate ::" + (int) (sendRate * 100));
                        // pb.setProgress(sendRate);

                        fout.write( bytes );
                        fout.flush();
                        updateMessage( (int) (sendRate * 100) + "%   " + (int) (fileLen / 1024) + "KB/" + (int) (allFileLen / 1024) + "KB" );
                        // updateTitle(fileLen+"/");
                        updateProgress( (int) (sendRate * 100), 100 );

                    }

                    // pb.setProgress(100);

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void succeeded() {
                // TODO Auto-generated method stub
                int splitPos = 0;
                System.out.println( " Copy File -----------------Sucess ...." );
                String fitlType = "", installPath = "";
                RarCompressUtils tarCompressUtils = new RarCompressUtils();
                Zip4jCompressUtil zip4jCompressUtil = new Zip4jCompressUtil();
                try {
                    fin.close();
                    fout.close();
                    // System.out.println(fileName+"--------------------- $$$$
                    // ::: fin.close()");

                    splitPos = fileName.lastIndexOf( "." );
                    installPath = fileName.substring( 0, splitPos );
                    fitlType = fileName.substring( splitPos + 1, fileName.length() );
                    System.out.println( " fileType ::: " + fitlType );

                    if (fitlType.toUpperCase().equals( "RAR" )) {

                        System.out.println( " dest File Path :::" + destFilePath );
                        System.out.println( " destPath :::" + destPath );
                        tarCompressUtils.unrar( destFilePath, destPath );

                    }

                    if (fitlType.toUpperCase().equals( "ZIP" )) {
                        System.out.println( " dest File Path :::" + destFilePath );
                        System.out.println( " destPath :::" + destPath );
                        File[] files = zip4jCompressUtil.unzip( destFilePath, "" );
                        for (int i = 0; i < files.length; i++) {
                            System.out.println( files[i] );
                        }

                    }
                    if (projectName.indexOf( "Tomcat" ) > -1) {

                        FileReader reader = new FileReader( destPath + "//" + installPath + "//conf//" + "server.xml" );
                        BufferedReader br = new BufferedReader( reader );

                        FileWriter writer = new FileWriter( destPath + "//" + installPath + "//conf//" + "server.xml.bak" );
                        BufferedWriter bw = new BufferedWriter( writer );

                        String str = null;

                        while ((str = br.readLine()) != null) {
                            // sb.append(str+"/n");

                            System.out.println( str );

                            String regEx = "Connector port|protocol|HTTP"; // 表示a或f
                            Pattern p = Pattern.compile( regEx );
                            Matcher m = p.matcher( str );
                            // boolean result=m.find();

                            int pos = 0;
                            while (m.find()) {
                                pos++;
                            }
                            if (pos == 3) {
                                System.out.println( "-----------------------------------****" + str );
                                bw.write( "<Connector port=\"" + settPort + "\" protocol=\"HTTP/1.1\" \n" );
                            } else {
                                bw.write( str + "\n" );
                            }
                        }

                        br.close();
                        reader.close();

                        bw.close();
                        writer.close();

                        File deleFile = new File( destPath + "//" + installPath + "//conf//" + "server.xml" );
                        deleFile.delete();

                        File changeFile = new File( destPath + "//" + installPath + "//conf//" + "server.xml.bak" );

                        // changeFile.renameTo(dest);
                        changeFile.renameTo( deleFile );
                    }
                    installBtn.setText( "安装" + projectName + "完成 " );

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                super.succeeded();
            }

            @Override
            protected void failed() {
                // TODO Auto-generated method stub
                System.out.println( "-----------------failed ...." );
                super.failed();
            }
        };

    }*/

    public Task sendPackageInfoByTask(final String projectName, String realinstallpath) throws IOException {
        // Label barLabel;
        String zipName = GlobalConfInfo.getProjectMap().get( projectName ).split( "," )[1];

        String sourceFilePath = System.getProperty( "user.dir" ) + "/package/" + zipName;
        //String sourceFilePath = this.getClass().getResource( "/package/" + zipName ).getPath();
        //BufferedReader reader = new BufferedReader( new InputStreamReader( this.getClass().getResourceAsStream( "/package/" + zipName ) ) );

        String destFilePath = destPath + "/" + fileName;

        File sourceFile = new File( sourceFilePath );
        File destFile = new File( destFilePath );


        FileInputStream fin = new FileInputStream( sourceFile );
        FileOutputStream fout = new FileOutputStream( destFile );

        return new Task<Void>() {

            // Label barLabel;
            /*String zipName = GlobalConfInfo.getProjectMap().get(projectName).split(",")[1];

			String sourceFilePath = System.getProperty("user.dir") + "/package/"+zipName;


            String destFilePath = destPath + "/" + fileName;

			File sourceFile = new File(sourceFilePath);
			File destFile = new File(destFilePath);


			FileInputStream fin = new FileInputStream(sourceFile);
			FileOutputStream fout = new FileOutputStream(destFile)*/;

            @Override
            protected Void call() throws Exception {

                byte[] bytes = new byte[1024];
                double fileLen = 0, allFileLen = 0;
                double sendRate = 0.0;
                try {

                    allFileLen = sourceFile.length();
                    System.out.println( " Source File Size ::" + allFileLen );
                    System.out.println( " 测试路径 ::" + destFilePath );
                    if (!destFile.exists()) {
                        destFile.createNewFile();
                    }

                    // bytes = new byte[1024];
                    while (fin.read( bytes ) != -1) {
                        if (isCancelled())
                            break;
                        fileLen = fileLen + bytes.length;
                        sendRate = (fileLen / allFileLen);
//						System.out.println("------- write File Len ::" + fileLen + " all FileLen::" + allFileLen
//								+ " rate ::" + (int) (sendRate * 100));
                        // pb.setProgress(sendRate);

                        fout.write( bytes );
                        fout.flush();
                        updateMessage( (int) (sendRate * 100) + "%   " + (int) (fileLen / 1024) + "KB/" + (int) (allFileLen / 1024) + "KB" );
                        // updateTitle(fileLen+"/");
                        updateProgress( (int) (sendRate * 100), 100 );

                    }

                    // pb.setProgress(100);

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void succeeded() {
                // TODO Auto-generated method stub
                int splitPos = 0;
                System.out.println( " Copy File -----------------Sucess ...." );
                String fitlType = "", installPath = "";
                /*RarCompressUtils tarCompressUtils = new RarCompressUtils();
                Zip4jCompressUtil zip4jCompressUtil = new Zip4jCompressUtil();*/
                try {
                    fin.close();
                    fout.close();
                    // System.out.println(fileName+"--------------------- $$$$
                    // ::: fin.close()");

                    //windows
                    splitPos = fileName.lastIndexOf( "." );
                    installPath = fileName.substring( 0, splitPos );
                    fitlType = fileName.substring( splitPos + 1, fileName.length() );
                    System.out.println( " fileType ::: " + fitlType );
                    //windows解压
                    if (StringUtils.isWindowPath( realinstallpath )) {
                        RarCompressUtils tarCompressUtils = new RarCompressUtils();
                        Zip4jCompressUtil zip4jCompressUtil = new Zip4jCompressUtil();
                        if (fitlType.toUpperCase().equals( "RAR" )) {

                            System.out.println( " dest File Path :::" + destFilePath );
                            System.out.println( " destPath :::" + destPath );
                            tarCompressUtils.unrar( destFilePath, destPath );

                        }

                        if (fitlType.toUpperCase().equals( "ZIP" )) {
                            System.out.println( " dest File Path :::" + destFilePath );
                            System.out.println( " destPath :::" + destPath );
                            File[] files = zip4jCompressUtil.unzip( destFilePath, "" );
                            for (int i = 0; i < files.length; i++) {
                                System.out.println( files[i] );
                            }

                        }
                    }
                    //linux环境解压
                    if (!StringUtils.isWindowPath( realinstallpath )) {
                        splitPos = fileName.lastIndexOf( "." );
                        installPath = fileName.substring( 0, splitPos );
                        installPath = installPath.substring( 0,installPath.lastIndexOf( "." ) );
                        fitlType = fileName.substring( splitPos + 1, fileName.length() );
                        System.out.println( " fileType ::: " + fitlType );
                        System.out.println( "linux tomcat install path :" + realinstallpath );
                        Firing firing = new Firing();
                        //firing.excutetomcatlinux( "unzip -d " + realinstallpath + " "+realinstallpath+"/"+fileName  );
                        System.out.println( "command :" +
                                "tar -zxvf " + realinstallpath + "/"+fileName + " -C " +realinstallpath );
                        /*Task task = firing.excutetomcatlinux2( new String[]{"/bin/sh", "-c", "tar -zxvf " + realinstallpath + "/" + fileName + " -C " + realinstallpath} );
                        Thread thread = new Thread( task, "linux command" );
                        thread.start();*/
                        firing.executeLinux2( new String[]{"/bin/sh", "-c", "tar -zxvf " + realinstallpath + "/" + fileName + " -C " + realinstallpath} );
                        System.out.println( "linux command succeed" );

                    }

                    if (projectName.indexOf( "Tomcat" ) > -1) {

                        FileReader reader = new FileReader( destPath + "//" + installPath + "//conf//" + "server.xml" );
                        BufferedReader br = new BufferedReader( reader );

                        FileWriter writer = new FileWriter( destPath + "//" + installPath + "//conf//" + "server.xml.bak" );
                        BufferedWriter bw = new BufferedWriter( writer );

                        String str = null;

                        while ((str = br.readLine()) != null) {
                            // sb.append(str+"/n");

                            System.out.println( str );

                            String regEx = "Connector port|protocol|HTTP"; // 表示a或f
                            Pattern p = Pattern.compile( regEx );
                            Matcher m = p.matcher( str );
                            // boolean result=m.find();

                            int pos = 0;
                            while (m.find()) {
                                pos++;
                            }
                            if (pos == 3) {
                                System.out.println( "-----------------------------------****" + str );
                                bw.write( "<Connector port=\"" + settPort + "\" protocol=\"HTTP/1.1\" \n" );
                            } else {
                                bw.write( str + "\n" );
                            }
                        }

                        br.close();
                        reader.close();

                        bw.close();
                        writer.close();

                        File deleFile = new File( destPath + "//" + installPath + "//conf//" + "server.xml" );
                        deleFile.delete();

                        File changeFile = new File( destPath + "//" + installPath + "//conf//" + "server.xml.bak" );

                        // changeFile.renameTo(dest);
                        changeFile.renameTo( deleFile );
                    }
                    installBtn.setText( "安装" + projectName + "完成 " );

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                super.succeeded();
            }

            @Override
            protected void failed() {
                // TODO Auto-generated method stub
                System.out.println( "-----------------failed ...." );
                super.failed();
            }
        };

    }

    public Button getInstallBtn() {
        return installBtn;
    }

    public void setInstallBtn(Button installBtn) {
        this.installBtn = installBtn;
    }

    //将web的war包解压到tomcat的webapps里
    public Task sendPackageInfoByTaskWithWeb(String projectName) throws IOException {

        return new Task<Void>() {

            // Label barLabel;
            //String warName = GlobalConfInfo.getProjectMap().get( projectName ).split( "," )[1];
            String warName = fileName;

            //String sourceFilePath = System.getProperty("user.dir") + "\\"+"package"+"\\"+warName;
            String sourceFilePath = System.getProperty( "user.dir" ) + "/package/" + warName;

            //String destFilePath = destPath + "\\" + "webapps"+"\\";
            String destFilePath = destPath + "/webapps/" + fileName;

            File sourceFile = new File( sourceFilePath );
            File destFile = new File( destFilePath );

            FileInputStream fin = new FileInputStream( sourceFile );
            FileOutputStream fout = new FileOutputStream( destFile );

            @Override
            protected Void call() throws Exception {

                byte[] bytes = new byte[1024];
                double fileLen = 0, allFileLen = 0;
                double sendRate = 0.0;
                try {

                    allFileLen = sourceFile.length();
                    System.out.println( " Source File Size ::" + allFileLen );
                    System.out.println( " 测试路径 ::" + destFilePath );
                    if (!destFile.exists()) {
                        destFile.createNewFile();
                    }

                    // bytes = new byte[1024];
                    while (fin.read( bytes ) != -1) {
                        if (isCancelled())
                            break;
                        fileLen = fileLen + bytes.length;
                        sendRate = (fileLen / allFileLen);
//						System.out.println("------- write File Len ::" + fileLen + " all FileLen::" + allFileLen
//								+ " rate ::" + (int) (sendRate * 100));
                        // pb.setProgress(sendRate);

                        fout.write( bytes );
                        fout.flush();
                        updateMessage( (int) (sendRate * 100) + "%   " + (int) (fileLen / 1024) + "KB/" + (int) (allFileLen / 1024) + "KB" );
                        // updateTitle(fileLen+"/");
                        updateProgress( (int) (sendRate * 100), 100 );

                    }

                    // pb.setProgress(100);

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void succeeded() {
                // TODO Auto-generated method stub
                int splitPos = 0;
                System.out.println( " Copy File -----------------Sucess ...." );
                String fitlType = "", installPath = "";
               /* RarCompressUtils tarCompressUtils = new RarCompressUtils();
                Zip4jCompressUtil zip4jCompressUtil = new Zip4jCompressUtil();*/
                try {
                    fin.close();
                    fout.close();
                    // System.out.println(fileName+"--------------------- $$$$
                    // ::: fin.close()");

                   /* splitPos = fileName.lastIndexOf(".");
                    installPath = fileName.substring(0, splitPos);
                    fitlType = fileName.substring(splitPos + 1, fileName.length());
                    System.out.println(" fileType ::: " + fitlType);*/

                    /*if (fitlType.toUpperCase().equals("RAR")) {

                        System.out.println(" dest File Path :::" + destFilePath);
                        System.out.println(" destPath :::" + destPath);
                        tarCompressUtils.unrar(destFilePath, destPath);

                    }

                    if (fitlType.toUpperCase().equals("ZIP")) {
                        System.out.println(" dest File Path :::" + destFilePath);
                        System.out.println(" destPath :::" + destPath);
                        File[] files = zip4jCompressUtil.unzip(destFilePath, "");
                        for (int i = 0; i < files.length; i++) {
                            System.out.println(files[i]);
                        }

                    }*/
                   /* if (projectName.indexOf("Tomcat") > -1) {

                        FileReader reader = new FileReader(destPath + "//" + installPath + "//conf//" + "server.xml");
                        BufferedReader br = new BufferedReader(reader);

                        FileWriter writer = new FileWriter(destPath + "//" + installPath + "//conf//" + "server.xml.bak");
                        BufferedWriter bw = new BufferedWriter(writer);

                        String str = null;

                        while ((str = br.readLine()) != null) {
                            // sb.append(str+"/n");

                            System.out.println(str);

                            String regEx = "Connector port|protocol|HTTP"; // 表示a或f
                            Pattern p = Pattern.compile(regEx);
                            Matcher m = p.matcher(str);
                            // boolean result=m.find();

                            int pos = 0;
                            while (m.find()) {
                                pos++;
                            }
                            if (pos == 3) {
                                System.out.println("-----------------------------------****" + str);
                                bw.write("<Connector port=\"" + settPort + "\" protocol=\"HTTP/1.1\" \n");
                            } else {
                                bw.write(str + "\n");
                            }
                        }

                        br.close();
                        reader.close();

                        bw.close();
                        writer.close();

                        File deleFile = new File(destPath + "//" + installPath + "//conf//" + "server.xml");
                        deleFile.delete();

                        File changeFile = new File(destPath + "//" + installPath + "//conf//" + "server.xml.bak");

                        // changeFile.renameTo(dest);
                        changeFile.renameTo(deleFile);
                    }*/
                    installBtn.setText( "安装" + projectName + "完成 " );

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                super.succeeded();
            }

            @Override
            protected void failed() {
                // TODO Auto-generated method stub
                System.out.println( "-----------------failed ...." );
                super.failed();
            }
        };

    }
}
